package org.leo.dm.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * Created on 2015年10月23日
 * <p>
 * Description 输出相关工具类
 * <p>
 * Copyright neusoft (c) 2015 .
 * 
 * @author xiao_h
 *
 */
public class ToUtil {
	static Logger log = LoggerFactory.getLogger(ToUtil.class);

	private long start;

	private double duration;

	private Runtime run = Runtime.getRuntime();

	private final int btom = 1024 * 1024;
	private final double ntos = 1000.00;

	private long totalMemory;
	private long maxMemory;
	private long freeMemory;

	public ToUtil() {
		start = System.currentTimeMillis();
	}

	public ToUtil showMemory() {
		totalMemory = run.totalMemory();
		maxMemory = run.maxMemory();
		freeMemory = run.freeMemory();
		ToUtil.to("MAXMEMORY（MB） = " + (maxMemory / btom) + " TOTALMEMORY（MB） = " + (totalMemory / btom) + " FREEMEMORY（MB） = " + (freeMemory / btom));
		return this;
	}

	private boolean time = true;

	private void getTimeDiff() {
		this.duration = (System.currentTimeMillis() - start) / ntos;
	}

	public void ignoreTime() {
		time = false;
	}

	public void takeTime() {
		takeTime(null, null);
	}

	public void takeTimePrex(String prex) {
		takeTime(prex, null);
	}

	public void takeTimeEnd(String end) {
		takeTime(null, end);
	}

	/**
	 * 返回值单位second
	 */
	public double getDuration() {
		getTimeDiff();
		return duration;
	}

	public void takeTime(String prex, String end) {
		if (time) {
			if (prex == null) {
				prex = "";
			}
			if (end == null) {
				end = "";
			}
			out(Thread.currentThread().getName() + " " + prex + " duration:" + this.getDuration() + " " + end);
		}
	}

	private static boolean to = true;

	public static void setTo(boolean to) {
		ToUtil.to = to;
	}

	public static void to(String str) {
		if (to) {
			out(str);
		}
	}

	private static boolean toq;

	public static void setToq(boolean toq) {
		ToUtil.toq = toq;
	}

	public static Object[] to(Object[] os) {
		if (toq) {
			StringBuffer sbu = new StringBuffer();
			sbu.append("阻塞队列数据打印：--");
			for (int i = 0; i < os.length; i++) {
				sbu.append(os[i] + "--");
			}
			out(sbu.toString());
		}
		return os;
	}

	private static void out(String str) {
		log.info(str);
	}

	public static void main(String[] args) {
		ToUtil toUtil = new ToUtil();
		try {
			Thread.sleep(1990);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		ToUtil.to(String.valueOf(toUtil.showMemory().getDuration()));
	}
}
